package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// MemberCard 会员卡模型
type MemberCard struct {
	BaseModel
	MemberId       int64  `orm:"column(member_id)" json:"member_id"`             // 会员ID
	CardNo         string `orm:"column(card_no);size(50)" json:"card_no"`        // 卡号
	LevelId        int64  `orm:"column(level_id)" json:"level_id"`               // 会员等级ID
	ValidityPeriod int    `orm:"column(validity_period)" json:"validity_period"` // 有效期(月)
	ExpiryDate     int64  `orm:"column(expiry_date)" json:"expiry_date"`         // 到期日期
	Status         int    `orm:"column(status)" json:"status"`                   // 状态：active-正常，expired-已过期，suspended-已挂起
	Remark         string `orm:"column(remark);size(500)" json:"remark"`         // 备注
}

// TableName 设置表名
func (m *MemberCard) TableName() string {
	return "ss_member_card"
}

// GetMemberCardList 获取会员卡列表
func GetMemberCardList(page, pageSize int, filters map[string]interface{}) (cards []*MemberCard, total int64, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MemberCard))

	// 应用过滤条件
	if keyword, ok := filters["keyword"].(string); ok && keyword != "" {
		qs = qs.SetCond(orm.NewCondition().Or("card_no__icontains", keyword).Or("member_id__in", GetMemberIdsByKeyword(keyword)))
	}
	if levelId, ok := filters["levelId"].(int64); ok {
		qs = qs.Filter("level_id", levelId)
	}
	if status, ok := filters["status"].(int); ok {
		qs = qs.Filter("status", status)
	}
	if startTime, ok := filters["startTime"].(int64); ok {
		qs = qs.Filter("created_at__gte", startTime)
	}
	if endTime, ok := filters["endTime"].(int64); ok {
		qs = qs.Filter("created_at__lte", endTime)
	}

	// 加盟商权限过滤
	if franchiseId, ok := filters["franchiseId"].(int64); ok && franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ = qs.Count()

	// 分页查询
	offset := (page - 1) * pageSize
	_, err = qs.OrderBy("-created_at").Limit(pageSize, offset).All(&cards)
	if err != nil {
		return nil, 0, err
	}

	return cards, total, nil
}

// GetMemberIdsByKeyword 根据关键词获取会员ID列表
func GetMemberIdsByKeyword(keyword string) []int64 {
	o := orm.NewOrm()
	var members []*Member
	qs := o.QueryTable(new(Member))
	// 应用过滤条件
	_, err := qs.SetCond(orm.NewCondition().Or("name__icontains", keyword).Or("phone__icontains", keyword)).All(&members, "id")
	if err != nil {
		return []int64{}
	}

	ids := make([]int64, len(members))
	for i, member := range members {
		ids[i] = member.Id
	}
	return ids
}

// GetMemberCardById 根据ID获取会员卡
func GetMemberCardById(id int64) (*MemberCard, error) {
	o := orm.NewOrm()
	card := &MemberCard{BaseModel: BaseModel{Id: id}}
	err := o.Read(card)
	if err != nil {
		return nil, err
	}

	return card, nil
}

// GetMemberCardByIdWithFranchise 根据ID获取会员卡（支持加盟商权限过滤）
func GetMemberCardByIdWithFranchise(id int64, franchiseId int64) (*MemberCard, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MemberCard)).Filter("id", id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	card := &MemberCard{}
	err := qs.One(card)
	return card, err
}

// CreateMemberCard 创建会员卡
func CreateMemberCard(card *MemberCard) (int, error) {
	o := orm.NewOrm()
	id, err := o.Insert(card)
	return int(id), err
}

// UpdateMemberCard 更新会员卡
func UpdateMemberCard(card *MemberCard) error {
	o := orm.NewOrm()
	_, err := o.Update(card)
	return err
}

// UpdateMemberCardWithFranchise 更新会员卡（支持加盟商权限过滤）
func UpdateMemberCardWithFranchise(card *MemberCard, franchiseId int64) error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MemberCard)).Filter("id", card.Id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	existingCard := &MemberCard{}
	err := qs.One(existingCard)
	if err != nil {
		return err
	}

	_, err = o.Update(card)
	return err
}

// DeleteMemberCard 删除会员卡
func DeleteMemberCard(id int64) error {
	o := orm.NewOrm()
	_, err := o.Delete(&MemberCard{BaseModel: BaseModel{Id: id}})
	return err
}

// DeleteMemberCardWithFranchise 删除会员卡（支持加盟商权限过滤）
func DeleteMemberCardWithFranchise(id int64, franchiseId int64) error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MemberCard)).Filter("id", id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	card := &MemberCard{}
	err := qs.One(card)
	if err != nil {
		return err
	}

	card.IsDeleted = 1
	_, err = o.Update(card, "IsDeleted")
	return err
}
